home *** CD-ROM | disk | FTP | other *** search
- // CPROG18.CPP
- // A very simple object - Ctrl+F9 to compile and run, Alt+F5 to see output
-
-
- #include <iostream.h> // Needed for cout and <<
-
- class testobj {
- int x, y; // x and Y are private to testobj. Only member
- // functions are able to access them
- public:
- testobj(void); // Constructor - automatically executed when a
- // testobj object is created.
- ~testobj(void); // Destructor - executed when object destroyed
- void printvals(void); // A member function of testobj - the only way
- // for the outside world to access x and y.
- };
-
- testobj::testobj(void) // Defintion of constructor function
- {
- x=10; //...it simply initialises x and y
- y=20; // and prints a message
- cout << "A testobj-type object has been created\n";
- }
-
- testobj::~testobj() // Definition of destructor function
- { //...it just prints a message
- cout << "A testobj-type object is being destroyed!\n";
- }
-
- void testobj::printvals(void) // Definition of printvals()
- {
- cout << "x=" << x << '\n'; //...prints values of x and y
- cout << "y=" << y << '\n';
- }
-
- //So far we have only said what a testobj-type object looks like. None actual
- //objects have been created.
- /////////////////////////////////////////////////////////////////////////////
- void main(void) // Program execution starts here
- {
- testobj fred; // An instance of testobj is created, called
- // fred. At this point the constructor will
- // be executed.
-
- fred.printvals(); // Use printvals() member function to see
- // values of x and y.
- } // End of program. Fred is destroyed as the
- // program cleans up before returning to DOS,
- // so the destructor is executed, causing the
- // farewell message to be printed.
- /////////////////////////////////////////////////////////////////////////////
- // Something to try - make fred an array of five objects... testobj fred[5];
- // and access one of those objects, eg fred[2].printvals();